package io.shuttle.mbe

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import io.shuttle.mbe.core.Promise

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException

/**
 * Instrumented test, which will execute on an Android device.
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest1 {
    @Test
    fun useAppContext() {
        // Context of the app under test.
        val appContext = InstrumentationRegistry.getInstrumentation().targetContext
        assertEquals("io.shuttle.mbe_core", appContext.packageName)
    }

    var testCount = 0
    var passedCount = 0

    @Test
    fun functionability() {
        println("=== AndroidPromise 测试开始 ===\n");
        // 运行所有测试
        testBasicResolve();
        testBasicReject();
        testChaining();
        testErrorHandling();
        testFutureInterface();
        testCancellation();
        testStaticMethods();
        testPromiseAll();
        testTimeout();
        testThreadSafety();
        // 等待异步测试完成
        try {
            Thread.sleep(5000)
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }

        // 输出测试结果
        println("\n=== 测试结果 ===")
        println("总测试数: $testCount")
        println("通过测试: $passedCount")
        println("失败测试: " + (testCount - passedCount))
        println("成功率: " + (passedCount * 100 / testCount) + "%")
    }

    fun testTimeout() {
        println("测试9: 超时功能")
        testCount++

        val promise: Promise<String?> = Promise { resolve, reject ->
            Thread(Runnable {
                try {
                    Thread.sleep(2000) // 2秒延迟
                    resolve?.resolve("延迟结果")
                } catch (e: InterruptedException) {
                    reject?.reject(e)
                }
            }).start()
        }

        try {
            promise.get(500, TimeUnit.MILLISECONDS) // 500ms 超时
            println("  ✗ 应该超时但没有超时")
        } catch (e: TimeoutException) {
            passedCount++
            println("  ✓ 超时功能正常")
        } catch (e: java.lang.Exception) {
            println("  ✗ 超时测试异常: " + e.message)
        }
        println()
    }

    fun testPromiseAll() {
        println("测试8: Promise.all")
        testCount++

        val latch = CountDownLatch(1)
        val success = booleanArrayOf(false)

        val promises: MutableList<Promise<String?>> = mutableListOf(
            Promise.resolve("任务1"),
            Promise.resolve("任务2"),
            Promise.resolve("任务3")
        )

        Promise.all<String>(promises)
            .then { results ->
                if (results!!.size == 3 &&
                    "任务1" == results[0] &&
                    "任务2" == results[1] &&
                    "任务3" == results[2]
                ) {
                    success[0] = true
                    println("  ✓ Promise.all 正常")
                } else {
                    println("  ✗ Promise.all 结果异常")
                }
                latch.countDown()
                results
            }

        try {
            latch.await(2, TimeUnit.SECONDS)
            if (success[0]) passedCount++
        } catch (e: InterruptedException) {
            println("  ✗ 测试超时")
        }
        println()
    }

    fun testStaticMethods() {
        println("测试7: 静态方法")
        testCount++

        val latch = CountDownLatch(2)
        val successCount = intArrayOf(0)


        // 测试 resolve
        Promise.resolve("静态resolve")
            .then { result ->
                if ("静态resolve" == result) {
                    successCount[0]++
                    println("  ✓ Promise.resolve 正常")
                } else {
                    println("  ✗ Promise.resolve 异常")
                }
                latch.countDown()
                result
            }


        // 测试 reject
        Promise.reject<String>(java.lang.RuntimeException("静态reject"))
            .catchError { error ->
                if ("静态reject" == error?.message) {
                    successCount[0]++
                    println("  ✓ Promise.reject 正常")
                } else {
                    println("  ✗ Promise.reject 异常")
                }
                latch.countDown()
                "默认值"
            }

        try {
            latch.await(1, TimeUnit.SECONDS)
            if (successCount[0] == 2) passedCount++
        } catch (e: InterruptedException) {
            println("  ✗ 测试超时")
        }
        println()
    }

    fun testCancellation() {
        println("测试6: 取消功能")
        testCount++

        val promise: Promise<String?> = Promise { resolve, reject ->
            Thread(Runnable {
                try {
                    Thread.sleep(1000)
                    resolve?.resolve("不应该看到这个")
                } catch (e: InterruptedException) {
                    reject?.reject(e)
                }
            }).start()
        }


        // 立即取消
        val cancelled: Boolean = promise.cancel(true)

        if (cancelled && promise.isCancelled && promise.isDone) {
            passedCount++
            println("  ✓ 取消功能正常")
        } else {
            println("  ✗ 取消功能异常")
        }
        println()
    }

    fun testFutureInterface() {
        println("测试5: Future 接口")
        testCount++

        val promise: Promise<String?> = Promise { resolve, reject ->
            Thread(Runnable {
                try {
                    Thread.sleep(200)
                    resolve?.resolve("Future测试")
                } catch (e: InterruptedException) {
                    reject?.reject(e)
                }
            }).start()
        }

        try {
            // 测试 get() 方法
            val result: String? = promise.get(1, TimeUnit.SECONDS)

            if ("Future测试" == result && promise.isDone && !promise.isCancelled) {
                passedCount++
                println("  ✓ Future 接口正常")
            } else {
                println("  ✗ Future 接口异常")
            }
        } catch (e: Exception) {
            println("  ✗ Future 接口异常: " + e.message)
        }
        println()
    }

    fun testErrorHandling() {
        println("测试4: 错误处理")
        testCount++

        val latch = CountDownLatch(1)
        val success = booleanArrayOf(false)

        val promise: Promise<String?> = Promise { resolve, reject ->
            resolve?.resolve("初始值")
        }

        promise
            .then<String> { result ->
                throw java.lang.RuntimeException("中间错误")
            }
            .catchError { error ->
                if ("中间错误" == error?.message) {
                    return@catchError "错误已恢复"
                }
                return@catchError "未知错误"
            }
            .then { result ->
                if ("错误已恢复" == result) {
                    success[0] = true
                    println("  ✓ 错误处理正常")
                } else {
                    println("  ✗ 错误处理失败: $result")
                }
                latch.countDown()
                result
            }

        try {
            latch.await(1, TimeUnit.SECONDS)
            if (success[0]) passedCount++
        } catch (e: InterruptedException) {
            println("  ✗ 测试超时")
        }
        println()
    }

    fun testChaining() {
        println("测试3: 链式调用")
        testCount++

        val latch = CountDownLatch(1)
        val success = booleanArrayOf(false)

        val promise: Promise<Int?> = Promise { resolve, reject ->
            resolve?.resolve(10)
        }

        promise
            .then { num -> num?.times(2) }
            .then { num -> num?.plus(5) }
            .then { result ->
                if (result != null && result == 25) {
                    success[0] = true
                    println("  ✓ 链式调用正常，结果: $result")
                } else {
                    println("  ✗ 链式调用结果错误: $result (期望: 25)")
                }
                latch.countDown()
                result
            }

        try {
            latch.await(1, TimeUnit.SECONDS)
            if (success[0]) passedCount++
        } catch (e: InterruptedException) {
            println("  ✗ 测试超时")
        }
        println()
    }

    fun testBasicReject() {
        println("测试2: 基本 reject 功能")
        testCount++

        val latch = CountDownLatch(1)
        val success = booleanArrayOf(false)

        val promise: Promise<String?> = Promise { resolve, reject ->
            Thread(Runnable {
                reject?.reject(RuntimeException("测试错误"))
            }).start()
        }

        promise.catchError { error ->
            if ("测试错误" == error?.message) {
                success[0] = true
                println("  ✓ reject 功能正常")
            } else {
                println("  ✗ reject 错误信息不正确: " + error?.message)
            }
            latch.countDown()
            "默认值"
        }

        try {
            latch.await(1, TimeUnit.SECONDS)
            if (success[0]) passedCount++
        } catch (e: InterruptedException) {
            println("  ✗ 测试超时")
        }
        println()
    }

    fun testBasicResolve() {
        println("测试1: 基本 resolve 功能")
        testCount++

        val latch = CountDownLatch(1)
        val success = booleanArrayOf(false)

        val promise: Promise<String?> = Promise { resolve, reject ->
            Thread(Runnable {
                try {
                    Thread.sleep(100)
                    resolve?.resolve("测试成功")
                } catch (e: InterruptedException) {
                    reject?.reject(e)
                }
            }).start()
        }

        promise.then { result ->
            if ("测试成功" == result) {
                success[0] = true
                println("  ✓ resolve 功能正常")
            } else {
                println("  ✗ resolve 结果不正确: $result")
            }
            latch.countDown()
            result
        }

        try {
            latch.await(1, TimeUnit.SECONDS)
            if (success[0]) passedCount++
        } catch (e: InterruptedException) {
            println("  ✗ 测试超时")
        }
        println()
    }

    fun testThreadSafety() {
        println("测试10: 线程安全")
        testCount++

        val latch = CountDownLatch(10)
        val successCount = intArrayOf(0)

        val promise: Promise<Int?> = Promise(fun(
            resolve: Promise.Resolver<Int?>?,
            reject: Promise.Rejector?
        ) {
            Thread(Runnable {
                try {
                    Thread.sleep(100)
                    resolve?.resolve(42)
                } catch (e: InterruptedException) {
                    reject?.reject(e)
                }
            }).start()
        })


        // 多个线程同时添加回调
        for (i in 0..9) {
            Thread(Runnable {
                promise.then { result ->
                    if (result != null && result == 42) {
                        synchronized(successCount) {
                            successCount[0]++
                        }
                    }
                    latch.countDown()
                    result
                }
            }).start()
        }

        try {
            latch.await(2, TimeUnit.SECONDS)
            if (successCount[0] == 10) {
                passedCount++
                println("  ✓ 线程安全正常")
            } else {
                println("  ✗ 线程安全异常，成功次数: " + successCount[0])
            }
        } catch (e: InterruptedException) {
            println("  ✗ 测试超时")
        }
        println()
    }
}